import React, { Fragment, useState, useEffect } from 'react';
import type { FC } from 'react';
import { Anchor, BackTop, message, Badge, Avatar, Typography } from 'antd';
import { ToTopOutlined, LikeOutlined, StarFilled } from '@ant-design/icons';
import { useRequest } from 'umi';
import { Line, Chart, Legend } from 'bizcharts';
import style from './index.less';
import 'highlight.js/styles/github.css'; // 引入github风格的代码高亮样式
import 'github-markdown-css'; // 引入github的markdown主题样式
import 'react-markdown-editor-lite/lib/index.css';
import { nextDay } from '@/utils/nextDay';
import { useParams } from 'umi';

import {
  articleLiked,
  getArticle,
  getOneArticleLiked,
  savePageView,
  saveCollect,
  getArticleCollect,
  cancelArticleCollect,
  getDateArticlePv
} from './service';
import hljs from 'highlight.js'; // 引入highlight.js库
// import 'highlight.js/styles/github.css'; // 引入github风格的代码高亮样式
import { marked } from 'marked';
import remarkGfm from 'remark-gfm';
import moment from 'moment';
const { Title } = Typography;
const { Link } = Anchor;
// import './github-markdown.css'
// npm i --save-dev @types/marked
const TurndownService = require('turndown').default;
// import * as aaa from 'turndown'
// npm install -g markedç
/**
 * turndown    https://www.npmjs.com/package/turndown
 * @returns
 */
const Detail: FC<Record<string, any>> = props => {
  const [ht, setHt] = useState('');
  const [articleId, setArticleId] = useState('');
  const [liked, setLiked] = useState({});
  const [collect, setCollect] = useState({});
  const [pvData, setPvData] = useState();
  const [collectStatus, setCollectStatus] = useState(true);
  const [titlePart, setTitlePart] = useState({
    // title:'',
    // user:'',
    // date:'',
    // userImg:'',
    // cover:''
  });
  const [show, setShow] = useState(true);
  marked.setOptions({
    renderer: new marked.Renderer(),
    highlight(code, language) {
      if (language && hljs.getLanguage(language)) {
        try {
          return `<br/><pre><code class="hljs language-${language}">${
            hljs.highlight(code, { language }).value
          }</code></pre>`;
        } catch (__) {}
      }
    },
    gfm: true, // 允许 Git Hub标准的markdown.
    pedantic: false, // 不纠正原始模型任何的不良行为和错误（默认为false）
    sanitize: false, // 对输出进行过滤（清理），将忽略任何已经输入的html代码（标签）
    breaks: false, // 允许回车换行（该选项要求 gfm 为true）
    smartLists: true, // 使用比原生markdown更时髦的列表
    smartypants: false, // 使用更为时髦的标点
  });
  const addLiked = () => {
    articleLiked({
      article_id: articleId,
      title: titlePart.title,
      author: titlePart.username,
      authoruser_id: titlePart.user_id,
      operateuser: localStorage.getItem('username'),
      operateuser_id: localStorage.getItem('user_id'),
    }).then(res => {
      res.data === 'have' && message.info('您已经赞过了');
      res.data === 'success' && message.success('点赞成功');
    });
    // 获得点赞
    getLiked(articleId);
  };
  const addCollect = () => {
    collect.count === 0 ?
      saveCollect({
        article_id: articleId,
        title: titlePart.title,
        author: titlePart.username,
        authoruser_id: titlePart.user_id,
        operateuser: localStorage.getItem('username'),
        operateuser_id: localStorage.getItem('user_id'),
      }).then(res => {
        res.data === 'success' && message.success('您已收藏');
        getCollect(articleId);
      }) :
      cancelArticleCollect({
        article_id: articleId,
        operateuser_id: localStorage.getItem('user_id'),
      }).then(res => {
        res.data === 'success' ? message.success('您已取消收藏') : message.error('取消失败');
        getCollect(articleId);
      });
  };
  const getCollect = (param: string) => {
    getArticleCollect({ article_id: param, operateuser_id: localStorage.getItem('user_id') }).then(
      res => {
        setCollect({ ...res.data[0] });
      }
    );
  };
  const getLiked = (param: string) => {
    getOneArticleLiked({ article_id: param, operateuser_id: localStorage.getItem('user_id') }).then(
      res => {
        setLiked({ ...res.data[0] });
      }
    );
  };
  const getDatePv = (param: string) => {
    getDateArticlePv({
      id: param,
      dateFrom: moment(new Date()).subtract(7, 'days').format('YYYY-MM-DD'),
      dateTo: moment(new Date()).format('YYYY-MM-DD'),
    }).then(res => {
      setPvData(nextDay(7,res.data));
    });
  };
  const {id} = useParams();

  useEffect(() => {
    const { user_id='' } = props?.history?.location?.state;
    getArticle({ id: id }).then(res => {
      const data = res.data[0];
      const { html } = data;
      html.replace(/ /gi, ' ');
      setHt(html);
      setTitlePart(data);
    });
    // 获得点赞
    getLiked(id);
    // 获得收藏
    getCollect(id);
    // 获得Pv统计数据
    getDatePv(id);
    user_id && savePageView({ id: id, user_id });
    setArticleId(id);
  }, []);

  return (
    <div className={style.container}>
      <div className={style.left}>
        <Anchor>
          {/* <Link href="#top" title={<LikeOutlined style={{ fontSize: 22 }} />} className={style.anchor} /> */}
          <div className={style.anchor} onClick={addLiked}>
            <Badge
              className="site-badge-count-109"
              count={liked ? liked.count : 0}
              style={{ backgroundColor: '#52c41a', top: '-7px', right: '-5px' }}
            >
              <LikeOutlined style={{ fontSize: 22, color: liked?.liked ? '#1e80ff' : '' }} />
            </Badge>
          </div>
          <div
            className={style.anchor}
            onClick={() => {
              addCollect(collectStatus);
            }}
          >
            <Badge
              className="site-badge-count-109"
              count={collect ? collect.count : 0}
              style={{ backgroundColor: '#52c41a', top: '-7px', right: '-5px' }}
            >
              <StarFilled style={{ fontSize: 22, color: collect?.count ? '#1e80ff' : '' }} />
            </Badge>
          </div>
        </Anchor>
      </div>
      <div className={style.center}>
        <div className={style.head_container}>
          <h1 title="top">
            <strong>{titlePart.title}</strong>
          </h1>
          <div className={style.info_con}>
            <Avatar src={titlePart.cover} className={style.photo} />
            <div className={style.text}>
              <div className={style.username}>{titlePart.username}</div>
              <div className={style.date}>{titlePart.updatedAt}</div>
            </div>
            <div className={style.editor}>

            </div>
          </div>
          <div className={style.cover_container}>
            {titlePart.cover && <img src={titlePart.cover} />}
          </div>
        </div>
        <div dangerouslySetInnerHTML={{ __html: marked(ht) }} className={style.detail_container} />
        <BackTop>
          <div style={{ width: 50, height: 40, fontSize: 20, textAlign: 'center' }}>
            <ToTopOutlined />
            <div style={{ fontSize: 10 }}>回到顶部</div>
          </div>
        </BackTop>
      </div>
      <div className={style.right}>
        <div className={style.chart_con}>
          <div className={style.title}>
            <Title level={5}> 近七日访问量</Title>
          </div>
          <Chart data={pvData} width={'100%'} height={290} autoFit className={style.chart}>
            <Legend />
            <Line position="date*count" visible={true} />
          </Chart>
        </div>
      </div>
    </div>
  );
};
export default Detail;
